#include<iostream>
#include<string>
#include <cstring>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include<unistd.h>

void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << " serverip serverport\n"<< std::endl;
}
int main(int argc,char *argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);//./client ip port
        exit(1);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);
    //创建套接字
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0)
    {
        std::cerr<<"socket error"<<std::endl;
        exit(2);
    }
    //构建目标主机的sock信息 struct sockaddr_in server
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    //发起连接
    int n = connect(sockfd,(struct sockaddr*)&server,sizeof(server));
    if(n<0)
    {
        std::cerr<<"connect error"<<std::endl;
        exit(3);
    }
    //连接完就可以通信了
    while(1)
    {
        std::cout<<"please Enter#";//客户端界面
        std::string outstring;
        getline(std::cin,outstring);
        //用一下send发送,前3个参数和write一样
        ssize_t s = send(sockfd,outstring.c_str(),outstring.size(),0);
        //发送成功
        if(s>0)
        {
            char inbuffer[1024];
            //准备接收服务端的
            ssize_t m = recv(sockfd,inbuffer,sizeof(inbuffer)-1,0);
            //接收成功
            if(m>0)
            {
                inbuffer[m]=0;
                std::cout<<inbuffer<<std::endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }
    close(sockfd);
    return 0;
}